package nanzhuli.user.svc.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import nanzhuli.user.svc.exception.ServiceException;
import nanzhuli.user.svc.model.resp.ozi.rest.HolidayResp;
import nanzhuli.user.svc.util.conf.DirectConnection;
import nanzhuli.user.svc.util.conf.ServiceNameConnection;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author luoqiang
 * @date 2020/10/23
 */
@Slf4j
@Component
public class RestTempClient {

    @Value("${nanzhuli.user.calendarUrl}")
    private String calendarUrl;

/*    @Bean(name = "innerSvcRestTemplate")
    @LoadBalanced
    @Conditional(ServiceNameConnection.class)
    public RestTemplate restTemplateLb() {
        return new RestTemplate();
        *//*return new RestTemplate(
				Arrays.asList(new HttpMessageConverter[] { new StringHttpMessageConverter(Charset.forName("UTF-8")) }));*//*
    }*/

    @Bean(name = "innerSvcRestTemplate")
//    @Conditional(DirectConnection.class)
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    @Resource
    @Qualifier("innerSvcRestTemplate")
    private RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "getHolidayInfosFallback", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000"),
            @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "4000"),})
    public String getHolidayInfos(String dateStr) throws Exception {
//        HttpHeaders httpHeaders = getHttpHeaders();
        Map<String, String> map = new HashMap<>();
        map.put("date", dateStr);
        map.put("resourceId", "6018");
        map.put("format", "json");

        long startTime = System.currentTimeMillis();
        log.info("万年历api远程调用开始,url={},入参={}", calendarUrl, JsonUtil.object2Json(map));
        ResponseEntity<String> getEntity = restTemplate.getForEntity(calendarUrl + "?query={date}&resource_id={resourceId}&format={format}", String.class, map);
        long endTime = System.currentTimeMillis();
        log.info("万年历api远程调用结束,出参={},耗时={}", JsonUtil.object2Json(getEntity), (endTime - startTime));

        if(null == getEntity || StringUtils.isEmpty(getEntity.getBody())){
            log.error("万年历api远程调用失败");
            throw new Exception("万年历api远程调用失败");
        }
        try {
            JSONObject jsonObject = JSONObject.parseObject(getEntity.getBody());
            // TODO 读取json处待优化
            Object objs = JsonUtil.getJsonFieldValue(jsonObject, "data.holiday").get(0);
            return JsonUtil.object2Json(objs);
        }catch (Exception e){
            log.error("》》》》》》解析" + calendarUrl + "返回json数据异常《《《《《" + e.getMessage());
            throw new Exception("》》》》》》解析" + calendarUrl + "返回json数据异常《《《《《");
        }
    }

    private HttpHeaders getHttpHeaders() {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        return headers;
    }

//    private JSONObject tryCatch(String str, String applicationName) throws Exception {
//        JSONObject jsonObject;
//        try {
//            jsonObject = JSONObject.parseObject(str);
//        } catch (Exception e) {
//            log.error("》》》》》》解析"+applicationName+"返回json数据异常《《《《《" + e.getMessage());
//            throw new Exception("》》》》》》解析"+applicationName+"返回json数据异常《《《《《");
//        }
//        if (!"0000".equals(jsonObject.get("code"))) {
//            throw new Exception("调用"+applicationName+"返回接口：" + jsonObject.get("msg"));
//        }
//        return jsonObject;
//    }

    private String getHolidayInfosFallback(String dateStr){
        log.error("调用百度万年历api超时，入参:{}", dateStr);
        throw new ServiceException("调用百度万年历api超时");
    }

}
